package com.zy.mc_module.ui.login;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.InputFilter;
import android.text.InputType;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import com.hwangjr.rxbus.RxBus;
import com.zy.mc_module.R;
import com.zy.mc_module.base.App;
import com.zy.mc_module.base.BaseActivity;
import com.zy.mc_module.common.Constant;
import com.zy.mc_module.common.RxBusCode;
import com.zy.mc_module.databinding.DialogCheckImgCodeBinding;
import com.zy.mc_module.mvp.bean.BaseBean;
import com.zy.mc_module.mvp.bean.ProtocolBean;
import com.zy.mc_module.mvp.bean.UserBean;
import com.zy.mc_module.mvp.contract.LoginContract;
import com.zy.mc_module.mvp.presenter.LoginPresenter;
import com.zy.mc_module.ui.main.AgreementActivity;
import com.zy.mc_module.ui.main.forget.ForgetActivity;
import com.zy.mc_module.utils.AppTools;
import com.zy.mc_module.utils.GlideUtil;
import com.zy.mc_module.utils.GsonUtil;
import com.zy.mc_module.utils.NoDoubleUtil;
import com.zy.mc_module.utils.SPUtil;
import com.zy.mc_module.utils.StatusBarUtil;
import com.zy.mc_module.utils.StringsUtils;
import com.zy.mc_module.utils.ToastUtil;
import com.zy.mc_module.utils.UserUtils;
import com.zy.mc_module.view.CustomHeadLayout;
import com.zy.mc_module.utils.retrofit.error.ThdException;
import com.zy.mc_module.wheel.dialog.CommonDialog;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnCheckedChanged;
import butterknife.OnClick;
import okhttp3.ResponseBody;

/**
 * @Date 19/3/15
 * @Author dq
 * 漂亮国度登录界面
 */
public class LoginActivity extends BaseActivity<LoginContract.View, LoginPresenter> implements
        LoginContract.View {

    @BindView(R.id.customhead)
    CustomHeadLayout customhead;
    @BindView(R.id.login_agreement)
    TextView tv_agreement;
    @BindView(R.id.registProtocol)
    TextView tv_registProtocol;
    @BindView(R.id.login_tel)
    EditText et_tel;
    @BindView(R.id.login_pwd)
    EditText et_pwd;
    @BindView(R.id.login_sure)
    TextView tv_sure;
    @BindView(R.id.login_relative_pwd)
    RelativeLayout relative_pwd;
    @BindView(R.id.login_agree_box)
    CheckBox agreeBox;
    @BindView(R.id.login_other_fun)
    View otherFunction;
    @BindView(R.id.login_get_code)
    TextView getCode;


    private int loginType = 1;
    private String tel, pwd, imgCode;
    private String registProtocol;
    private String title;
    private CommonDialog checkDialog;
    private DialogCheckImgCodeBinding dialogBinding;

    @Override
    protected LoginPresenter createPresenter() {
        return new LoginPresenter();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    protected void initView() {
        App.getInstance().addTmpActivity(this);
        StatusBarUtil.setImmersiveStatusBar(this);
        customhead.setLeftClickListener(view -> finish());
        presenter.queryArticleProtocol(context, "13", "1");//注册协议
        dialogBinding = DialogCheckImgCodeBinding.inflate(getLayoutInflater());
        checkDialog = new CommonDialog(context, false, dialogBinding.getRoot());

    }

    @Override
    protected void initListener() {
        super.initListener();
        customhead.setRightClickListener3(view -> {
            String loginTxt = tv_sure.getText().toString();
            if ("下一步".equals(loginTxt)) {
                pwdlg();
            } else if ("登录".equals(loginTxt)) {
                codelg();
            }
        });

        setDialogListener();
    }

    private void setDialogListener() {
        dialogBinding.dialogHintSwitch.setOnClickListener(v -> {
            getImgCode();
        });
        dialogBinding.hintCancel.setOnClickListener(v -> checkDialog.dismiss());
        dialogBinding.hintSure.setOnClickListener(v -> {
            String code = dialogBinding.hintContent.getText().toString();
            if (StringsUtils.isEmpty(code)) {
                ToastUtil.show("请输入验证码");
                return;
            }
            imgCode = code;
            presenter.getLoginCode(context, et_tel.getText().toString(), code);
        });
    }

    private void getImgCode() {
        if (NoDoubleUtil.isFastClick())
            presenter.getImgCode(context, tel);
    }

    /***
     * 验证码登录
     */
    public void codelg() {
        customhead.setRightText("密码登录");
        getCode.setVisibility(View.VISIBLE);
        loginType = 2;
        //relative_pwd.setVisibility(View.GONE);
        otherFunction.setVisibility(View.GONE);
        et_tel.setHint("请输入手机号");
        et_tel.setInputType(InputType.TYPE_CLASS_NUMBER);
        et_tel.setFilters(new InputFilter[]{new InputFilter.LengthFilter(11)});
        tv_sure.setText("下一步");
    }

    /***
     * 账号密码登录
     */
    public void pwdlg() {
        customhead.setRightText("验证码登录");
        loginType = 1;
        getCode.setVisibility(View.GONE);
        relative_pwd.setVisibility(View.VISIBLE);
        otherFunction.setVisibility(View.VISIBLE);
        et_tel.setHint("请输入用户名/手机号");
        et_tel.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
        et_tel.setFilters(new InputFilter[]{new InputFilter.LengthFilter(25)});
        tv_sure.setText("登录");
    }

    /***
     * 新用户注册
     */
    @OnClick(R.id.login_register)
    public void register() {
        startActivity(new Intent(this, RegisterActivity.class));
    }


    @Override
    public <T> void onSuccess(T t, int type) {
        if (type == LoginPresenter.IMG_CODE) {
            ResponseBody body = (ResponseBody) t;
            try {
                InputStream byteStream = body.byteStream();
                Bitmap bitmap = BitmapFactory.decodeStream(byteStream);
                GlideUtil.displayImage(dialogBinding.dialogHintImg, bitmap, R.mipmap.uvv_on_error);
                if (!checkDialog.isShowing()) {
                    checkDialog.show();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (type == 0) {
            BaseBean baseBean = (BaseBean) t;

        } else if (type == 1) {
            BaseBean<Boolean> baseBean = (BaseBean<Boolean>) t;
            if (!baseBean.data) {
                //下一步-获取验证码
                tel = et_tel.getText().toString().trim();
                presenter.getCode(context, "1", tel);
            } else {
                ToastUtil.showShort("手机号暂未注册");
            }
        } else if (type == 2) {
            ProtocolBean protocolBean = (ProtocolBean) t;
            if (!StringsUtils.isEmpty(protocolBean)) {
                if (!StringsUtils.isEmpty(registProtocol)) {
                    title = protocolBean.title;
                    //设置协议和点击事件
                    tv_agreement.setText("《" + registProtocol + "》");
                    tv_registProtocol.setText("《" + title + "》");
                } else {
                    registProtocol = protocolBean.title;//注册协议
                    presenter.queryArticleProtocol(context, "14", "1");//隐私政策
                }

            }
        }
    }

    /**
     * 用户协议/隐私政策
     */
    @OnClick({R.id.login_agreement, R.id.registProtocol})
    public void onViewClicked(View view) {
        Intent intent = new Intent(context, AgreementActivity.class);
        switch (view.getId()) {
            case R.id.login_agreement:
                intent.putExtra("articleProtocolType", "13");
                intent.putExtra("title", registProtocol);
                break;
            case R.id.registProtocol:
                intent.putExtra("articleProtocolType", "14");
                intent.putExtra("title", title);
                break;
        }
        startActivity(intent);
    }

    @OnClick(R.id.login_get_code)
    public void getCode() {
        tel = et_tel.getText().toString().trim();
        if (!agreeBox.isChecked()) {
            InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
            View v = getWindow().peekDecorView();
            if (null != v) {
                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
            }
            ToastUtil.show("请阅读并同意《注册协议》和《隐私注册》");
            return;
        }
        if (!StringsUtils.isPhoneNum(tel)) {
            ToastUtil.show("请输入正确的手机号获取验证码");
            return;
        }
        if (imgCode == null) {
            getImgCode();
        } else {
            presenter.getLoginCode(context, et_tel.getText().toString(), imgCode);
        }
    }

    /***
     * 下一步获取验证码/账号密码登录
     */
    @OnClick(R.id.login_sure)
    public void codeAndLogin() {
        if (NoDoubleUtil.isFastClick()) {
            if (!agreeBox.isChecked()) {
                InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
                View v = getWindow().peekDecorView();
                if (null != v) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
                ToastUtil.show("请阅读并同意《注册协议》和《隐私注册》");
                return;
            }
//            登录类型 1 账号密码登录 2 短信登录
            tel = et_tel.getText().toString().trim();
            pwd = et_pwd.getText().toString().trim().toLowerCase();
            presenter.login(context, loginType, tel, tel, pwd);
        }
    }

    /***
     * 忘记密码
     */
    @OnClick(R.id.login_forget)
    public void forget() {
        if (NoDoubleUtil.isFastClick()) {
            startActivity(new Intent(context, ForgetActivity.class));
        }
    }

    /***
     * 显示密码
     */
    @OnCheckedChanged(R.id.login_showpwd)
    public void show(boolean isChecked) {
        AppTools.hidePwd(et_pwd, isChecked);
    }

    /***
     * 获取验证码
     */
    @Override
    public void onGetCodeSuccess(String success) {
        ToastUtil.show("验证码已发送");
        if (checkDialog.isShowing())
            checkDialog.dismiss();

        count = 60;
        handler.sendEmptyMessage(MSG_WHART);
    }

    private void plus() {

    }

    public final int MSG_WHART = 1001;
    public int count = 60;
    Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_WHART: {
                    getCode.setEnabled(false);
                    if (count <= 0) {
                        getCode.setText("获取验证码");
                        getCode.setEnabled(true);
                    } else {
                        count--;
                        getCode.setText(count + "s");
                        handler.sendEmptyMessageDelayed(MSG_WHART, 1000);
                    }
                    break;
                }
            }
        }
    };

    /***
     * 账号密码登录成功
     */
    @Override
    public void onLoginSuccess(UserBean userBean) {
//        Map<String, Object> map = new HashMap<>();
//        SPUtil.putString(Constant.USER_H5_KEY, GsonUtil.gsonString(map));
//        UserUtils.saveUser(userBean);
        RxBus.get().post(RxBusCode.REFRESHUSER_POSITION, "");
        finish();

    }

    @Override
    public void onSuccess(boolean isSuc) {

    }

    @Override
    public void onError(ThdException error) {
        imgCode = null;//图像验证码失效
        ToastUtil.showShort(error.message);
    }
}
